#!/usr/bin/ruby

require 'lcd'
require 'rss/1.0'
require 'rss/2.0'
require 'open-uri'

### CONFIGURATION
# $source: feed location
$source = "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml"
# $name: title to put on line 1 of lcd display
$name = "BBC News"
### END CONFIGURATION

WAIT_TIME = 12

$lcd = LCD.new("lcdrss")
$lcd.proc_resp = true
$scr = [LCD::Screen.new("lcdrss1", "lcdrss", "normal"),
        LCD::Screen.new("lcdrss2", "lcdrss", "normal"),
        LCD::Screen.new("lcdrss3", "lcdrss", "normal"),
        LCD::Screen.new("lcdrss4", "lcdrss", "normal"),
        LCD::Screen.new("lcdrss5", "lcdrss", "normal")]

$lcd.trap_sigint()
$lcd.connect()

$title   = [LCD::Title.new($name),
            LCD::Title.new($name),
            LCD::Title.new($name),
            LCD::Title.new($name),
            LCD::Title.new($name)]
$article = [LCD::Scroller.new("Loading...", 1, 2, 20, 4, "v", 5),
            LCD::Scroller.new("Loading...", 1, 2, 20, 4, "v", 5),
            LCD::Scroller.new("Loading...", 1, 2, 20, 4, "v", 5),
            LCD::Scroller.new("Loading...", 1, 2, 20, 4, "v", 5),
            LCD::Scroller.new("Loading...", 1, 2, 20, 4, "v", 5)]

for i in (0..4)
    $scr[i].add_widgets($title[i], $article[i])
    $lcd.add_screen($scr[i])
end

def update_articles
   content = "" # raw content of rss feed will be loaded here
   open($source) do |s| content = s.read end
   rss = RSS::Parser.parse(content, false)
   for i in (0..4)
     $article[i].text = rss.items[i].title
     $lcd.update_screen($scr[i])
   end
end

begin
   update_articles()
   while (true)
      sleep(300)

      update_articles()

      stat = $lcd.get_status()
      puts "Got an error: #{stat.error}" if (stat.error)
   end
rescue
   puts "Aieee: " + $!.message
   puts $!.backtrace
end

$lcd.close()
